package com.Nuyoah.demo01.common;

import cn.dev33.satoken.stp.StpUtil;
import com.Nuyoah.demo01.VO.UserVO;
import com.Nuyoah.demo01.entity.User;
import com.Nuyoah.demo01.service.AdminService;
import com.Nuyoah.demo01.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; // 引入依赖注入注解
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 自定义拦截器
 * @author Nuyoah
 * @date 2025/02/16
 */
public class MyInterceptor implements HandlerInterceptor {


    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查handler是否是HandlerMethod类型
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            String methodName = method.getName();
            logger.info("====拦截到了方法：{}，在该方法执行之前执行====", methodName);
        } else {
            logger.info("====拦截到的不是HandlerMethod类型====");
        }

        // 使用Sa-Token验证Token
        try {
            StpUtil.checkLogin();
            logger.info("用户已登录，Token有效");

            // 获取当前登录用户的ID
            Integer userId = StpUtil.getLoginIdAsInt();

            // 从ApplicationContext中获取UserService和AdminService
            ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            UserService userService = context.getBean(UserService.class);
            AdminService adminService = context.getBean(AdminService.class);


            // 获取用户信息
            UserVO user = userService.getUserById(userId); // 此处可以正常调用userService
            //管理员判断
            //查询当前用户是否为管理员
            logger.info("用户ID: {}", userId);
            boolean isAdmin = adminService.isAdmin(userId);
            if (user != null && isAdmin) {
                logger.info("用户是管理员，可以访问");
                return true; // 管理员可以访问
            } else {
                logger.info("用户不是管理员，无权访问");
                return false; // 非管理员，拦截请求
            }
        } catch (Exception e) {
            logger.info("用户未登录，Token无效: {}", e.getMessage());
            return true; // 不拦截
//            return false; // 拦截请求
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("执行完方法之后进执行(Controller方法调用之后)，但是此时还没进行视图渲染");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("整个请求都处理完咯，DispatcherServlet也渲染了对应的视图咯，此时我可以做一些清理的工作了");
    }
}
